class IssuesController < ApplicationController
  #このコントローラ内のメソッドを行う前にログインチェック
  before_action :cheaklogin

       def cheaklogin
         if $logincheak == 0
             redirect_to login_path
         end
       end

  def index
    @issues = Issue.all
  end

  def search
    @issues = Issue.where('hid like ? or day like ? or useswname like ? or pcname like ? or user like ?', "%"+params[:q]+"%", "%"+params[:q]+"%", "%"+params[:q]+"%", "%"+params[:q]+"%", "%"+params[:q]+"%")
    render "index"
  end

  def show
  end

  def edit
    @issue = Issue.find(params[:id])
  end

  def new
    @issue = Issue.new

  end

  def create
     @issue = Issue.new(issue_params)
 #新規登録のエラー処理
     @software = Software.find_by(:swname => @issue.useswname)

     if @issue.hid.empty? || @issue.day.empty? || @issue.useswname.empty? || @issue.usekey.empty? || @issue.pcname.empty? || @issue.user.empty?
       redirect_to new_issue_path, :notice => "記入に不備があります"

     elsif @software.license == 0
        redirect_to new_issue_path, :notice => "残りライセンス数が０のため払出出来ません"

     elsif @software.productkey != @issue.usekey
       redirect_to new_issue_path, :notice => "プロダクトキーが違います"

     else @issue.save
 #新規登録に成功したら対象ソフトウェアのライセンスをー１
        @software.update_attributes(:license => @software.license - 1)
        redirect_to issues_url, :notice => "登録完了！"
     end

  end

  def update
    @issue = Issue.find(params[:id])
     if @issue.update(issue_params)
       redirect_to issues_url(@issue)
     else
       render 'edit'
     end
  end

  def destroy
    @issue = Issue.find(params[:id])
    @software = Software.find_by(:swname => @issue.useswname)
#登録内容を削除したら対象ソフトウェアのライセンスを＋１
    @software.update_attributes(:license => @software.license + 1)
    @issue.destroy
    redirect_to issues_url
  end

  private
   def issue_params
     params.require(:issue).permit(:hid, :day, :useswname, :usekey, :pcname, :user)
   end

 end
